package com.webmuseum.server;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Database {
	private static final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
	private static final String url = "jdbc:odbc:";

	
    
    
   
    
  
	

    public boolean InsertQuery(String query) throws ClassNotFoundException, SQLException
	{
    	Class.forName(driver);
        Connection connection = DriverManager.getConnection(url+GeneralDataSetting.mainDatabaseName, GeneralDataSetting.mainDatabaseUser, GeneralDataSetting.mainDatabasePass);
		boolean risultato;
		try
		{
			
			Statement stmt = connection.createStatement();
			risultato = stmt.execute(query);
			stmt.close();
			connection.close();
			
			
		}
		catch (Exception ex)
		{
			risultato = false;
			ex.printStackTrace();
			System.out.println("eccezione insert "+ex.getMessage());
		}
		
		return risultato;
	}

    public ResultSet SelectionQuery(String query) throws ClassNotFoundException, SQLException
	{
    	Class.forName(driver);
        Connection connection = DriverManager.getConnection(url+GeneralDataSetting.mainDatabaseName, GeneralDataSetting.mainDatabaseUser, GeneralDataSetting.mainDatabasePass);
		
		ResultSet risultato;
		try
		{
			Statement stmt = connection.createStatement();
			boolean result = stmt.execute(query);
			System.out.println(result);
			risultato = stmt.getResultSet();
			
			
		}
		catch (Exception ex)
		{
			risultato = null;
			ex.printStackTrace();
			System.out.println(ex.getMessage());
		}
		
		
		return risultato;
	}
    
	
    public int getMaxID(String aTable,String aReference) throws SQLException{
		
    	int index = -1;
    	String query = "SELECT MAX("+aReference+") AS result FROM "+aTable;	
    	System.out.println(query);
    	ResultSet result;
		try {
			result = SelectionQuery(query);
			if(result.next()) {
	    		index = result.getInt("result");
	    		
	    		}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
		
    	return index;
    	
    	}   

}
